package com.wlstock.funi.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.em.mission.Mission;
import com.em.mission.MissionQueue;
import com.em.mission.MissionResultListener;
import com.em.operate.util.FileUtil;
import com.maxleap.MLDataManager;
import com.maxleap.MLObject;
import com.maxleap.SaveCallback;
import com.maxleap.exception.MLException;
import com.wlstock.funi.MissionInstance.BuyXinMission;
import com.wlstock.funi.MissionInstance.KLineMissionQueue;
import com.wlstock.funi.MissionInstance.MinPeriodKLineMission;
import com.wlstock.funi.MissionInstance.MissionNameConstant;
import com.wlstock.funi.MissionInstance.StrategyMission;
import com.wlstock.funi.MissionInstance.WanLongStaMission;
import com.wlstock.funi.MissionInstance.YiMengPositionMission;
import com.wlstock.funi.MissionInstance.ZDFMission;
import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.constant.AssetResConstant;
import com.wlstock.funi.constant.SharePrefConstants;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.StrategyDao;
import com.wlstock.funi.dao.StrategyFundSelDao;
import com.wlstock.funi.dialog.PopTradeDialog;
import com.wlstock.funi.fundenum.KLINE_PERIOD;
import com.wlstock.funi.fundenum.TRADE_ERROR_STATE;
import com.wlstock.funi.model.BaseModel;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.PendTradeModel;
import com.wlstock.funi.model.PositionModel;
import com.wlstock.funi.model.SelfFundHisModel;
import com.wlstock.funi.model.StrategyFundModel;
import com.wlstock.funi.model.StrategyModel;
import com.wlstock.funi.runnable.CancelOrder;
import com.wlstock.funi.runnable.CancelOrder.CANCEL_CODE;
import com.wlstock.funi.runnable.CancelOrder.onCancelListener;
import com.wlstock.funi.runnable.CurPosition;
import com.wlstock.funi.runnable.CurPosition.CurPositionListener;
import com.wlstock.funi.runnable.OrderBuy;
import com.wlstock.funi.runnable.OrderSale;
import com.wlstock.funi.runnable.PendTradeList;
import com.wlstock.funi.runnable.PendTradeList.RESULT_CODE;
import com.wlstock.funi.runnable.PendTradeList.onResultListener;
import com.wlstock.funi.runnable.SysHisTrade;
import com.wlstock.funi.utils.BuyHelper;
import com.wlstock.funi.utils.SellHelper;
import com.wlstock.funi.utils.SharePreferenceUtils;
import com.wlstock.funi.utils.ToastUtils;
import com.wlstock.funi.utils.TradeManagerListener;

import org.apache.cordova.LOG;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class TestActivity extends FundBaseActivity implements  CurPositionListener, onResultListener, onCancelListener,MissionResultListener, MissionQueue.onMissionQueueListener, TradeManagerListener {

	private static final String STRATEGY = "STRATEGY";
	private static final String DAXIN = "DAXIN";

	private ListView lv_base;
	private TestActivity mContext;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_base_lv);
		mContext = this;
		lv_base = (ListView) findViewById(R.id.lv_base);
		
		ArrayList<String> items = new ArrayList<String>();
		items.add(getResources().getString(R.string.test_buy));
		items.add(getResources().getString(R.string.test_saile));
		items.add(getResources().getString(R.string.test_download));
		items.add(getResources().getString(R.string.test_trade));
		items.add(getResources().getString(R.string.test_pop));
		items.add(getResources().getString(R.string.test_curposition));
		items.add(getResources().getString(R.string.test_getPenTrade));
		items.add(getResources().getString(R.string.test_cancelorder));
		items.add(getResources().getString(R.string.test_local_data));
		items.add(getResources().getString(R.string.test_wengu_webview));
		items.add(getResources().getString(R.string.test_sys_his));
		items.add("测试查询最大持仓时间");
		items.add("测试WEBVIEW");
		items.add("测试打新");
		items.add("清除策略数据");
		items.add("测试加入策略");
		items.add("上传策略到MAXLEAP服务器");
		items.add("从Maxleap服务器获取策略数据");
		items.add("测试任务队列");
		items.add("测试自动买入");
		items.add("获取时分K线数据");
		items.add("获取日线数据");

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,items);
		lv_base.setAdapter(adapter);
		
		lv_base.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int arg2, long arg3) {
				TextView tv = (TextView) v.findViewById(android.R.id.text1);
				if (tv.getText().equals(getResources().getString(R.string.test_buy))) {
					OrderBuy buy = new OrderBuy("002055", "得润电子", 32.5f, 1000);
					buy.buy(null);
				}else if (tv.getText().equals(getResources().getString(R.string.test_saile))) {
					OrderSale saile = new OrderSale("600423", "柳化股份", SellHelper.getInstance(TestActivity.this).getPrice(7.39f), 1000);
					saile.saile(null);
				}else if (tv.getText().equals(getResources().getString(R.string.test_download))){
					//测试下载
//					DownloadTask task = new DownloadTask("http://quotes.money.163.com/service/chddata.html?code=0600288&start=20121129&end=20160223&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP",
//					Environment.getExternalStorageDirectory().getPath(), "0600288.csv", "test", null);
//					task.setThumbnail("file:///sdcard/hobbit.jpg");
//					DownloadTaskManager.getInstance(TestActivity.this).registerListener(task,TestActivity.this);
//					DownloadTaskManager.getInstance(TestActivity.this).startDownload(task);
				}else if (tv.getText().equals(getResources().getString(R.string.test_trade))) {
//					测试交易
					Intent selfFundIntent = new Intent(TestActivity.this, PopTradeDialog.class);
					startActivity(selfFundIntent);
				}else if (tv.getText().equals(getResources().getString(R.string.test_pop))) {
					//测试悬浮窗口
					LinearLayout layout = new LinearLayout(TestActivity.this);
					layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					layout.setOrientation(LinearLayout.VERTICAL);
					TextView tV = new TextView(TestActivity.this);
					tV.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
					layout.addView(tV);
					tV.setText("哼哼哈哈");
					tV.setTextSize(30);
					tV.setTextColor(getResources().getColor(R.color.white));
					FundApplication.getInstance().showDesk(layout);
				}else if (tv.getText().equals(getResources().getString(R.string.test_curposition))){
					//测试获取当前仓位
					CurPosition req = new CurPosition();
					req.resultListener = TestActivity.this;
					req.requset();
				}else if (tv.getText().equals(getResources().getString(R.string.test_getPenTrade))) {
					PendTradeList reqPendList = new PendTradeList();
					reqPendList.request(TestActivity.this);
//					try {
//						String cancelList = FileUtil.stream2Str(FileUtil.assetRes2Stream(getResources(), AssetResConstant.CACEL_QUEUE_DATAS));
//						PendTradeDao.getInstance(TestActivity.this).parsePendList(cancelList);
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
				}else if (tv.getText().equals(getResources().getString(R.string.test_cancelorder))){
					CancelOrder cancelOrder = new CancelOrder();
					cancelOrder.reqCancel(7, TestActivity.this);
				} else if (tv.getText().equals(getResources().getString(R.string.test_local_data))) {
					Intent i = new Intent(TestActivity.this, LocalDBActivity.class);
					startActivity(i);
				} else if (tv.getText().equals(getResources().getString(R.string.test_wengu_webview))) {
					startActivity(new Intent(TestActivity.this, ScrollTableActivity.class));
				} else if (tv.getText().equals(getResources().getString(R.string.test_sys_his))){
					try {
						String hisDatas = FileUtil.stream2Str(FileUtil.assetRes2Stream(getResources(), AssetResConstant.SYS_HIS_DATAS));
						SysHisTrade sysHisTrade = new SysHisTrade();
						sysHisTrade.parseHisDatas(hisDatas);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else if (tv.getText().equals("测试查询最大持仓时间")){
                    List<StrategyModel> strategyModels = StrategyDao.getInstance(TestActivity.this).queryAll();
//                    for (StrategyModel model : strategyModels){
//                        StrategyFundModel strategyFundModel = new StrategyFundModel(model);
//                        strategyFundModel.setStkNo("600811");
//                        strategyFundModel.setStkName("东方集团");
//                        try {
//                            strategyFundModel.setCreateDate("2016-09-04");
//                            strategyFundModel.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-04"));
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
//                        StrategyFundSelDao.getInstance(TestActivity.this).createOrUpdate(strategyFundModel);
//                    }
					MyAccountStocks tmpStock = new MyAccountStocks("600811", "东方集团", 1000, "12.0", "11.0", 0.6f, 1000,0.6f, 1000);
					tmpStock.setWithStraModel(StrategyFundSelDao.getInstance(TestActivity.this).queryStraModelWithCode(tmpStock.getStkCode()));
					MyAccountStockDao.getInstance(TestActivity.this).createOrUpdateStock(tmpStock);

//					String stkCode = "600811";
//					StrategyFundSelDao.getInstance(TestActivity.this).queryShouldKeepDays(stkCode);

				}
				else if (tv.getText().equals("测试WEBVIEW")){
					Intent intent = new Intent(TestActivity.this, TestWebView.class);
					startActivity(intent);
				}else if (tv.getText().equals("测试打新")){
					BuyXinMission mission = BuyXinMission.getInstance(TestActivity.this,MissionNameConstant.MISSION_BUYXIN);
					mission.start(TestActivity.this);
				}else  if (tv.getText().equals("测试加入策略")){
					StrategyMission strategyMission = StrategyMission.getInstance(TestActivity.this,MissionNameConstant.MISSION_STRATEGY);
					strategyMission.start(STRATEGY,TestActivity.this);
				}else  if (tv.getText().equals("清除策略数据")){
					StrategyFundSelDao.getInstance(TestActivity.this).deleteAll();
				}else if (tv.getText().equals("上传策略到MAXLEAP服务器")){
					List<StrategyFundModel> strategyFundModels = StrategyFundSelDao.getInstance(TestActivity.this).queryAll();
					saveStrategyModels(strategyFundModels);

					List<StrategyModel> strategyModels = StrategyDao.getInstance(TestActivity.this).queryAll();
					saveStrategyModels(strategyModels);

				}else if(tv.getText().equals("从Maxleap服务器获取策略数据")){
					StrategyFundSelDao.getInstance(TestActivity.this).sysFromServer();
				} else if (tv.getText().equals("测试任务队列")){
					Context mConxt = TestActivity.this;
					MissionQueue queue = new MissionQueue(mConxt, MissionNameConstant.MISSION_QUEUE_STA_ONCE);
//					MoneyFlowStaMission moneyFlowStaMission = new MoneyFlowStaMission(mConxt, MissionNameConstant.MISSION_MONEY_STA);
//					MarketStaticMission marketStaticMission = new MarketStaticMission(mConxt, MissionNameConstant.MISSION_DFCF_STA);
					YiMengPositionMission yiMengMission = YiMengPositionMission.getInstance(mConxt, MissionNameConstant.MISSION_YIMENG_POSITION);
					ZDFMission zdfMission = ZDFMission.getInstance(mConxt, MissionNameConstant.MISSION_WENGU_ZDF_STA);
					WanLongStaMission wanLongStaMission = WanLongStaMission.getInstance(mConxt, MissionNameConstant.MISSION_WANGLONG_STA);

					queue.addMission(yiMengMission).addMission(zdfMission).addMission(wanLongStaMission);
					queue.start(TestActivity.this);

				}else if(tv.getText().equals("测试自动买入")){
					BuyHelper.getInstance(TestActivity.this).autoBuy(SharePreferenceUtils.getBoolSP(TestActivity.this, SharePrefConstants.IS_AUTO_BUY_MODE,false),TestActivity.this);

				}else if(tv.getText().equals("获取K线数据")){

					KLineMissionQueue kLineMissions =  KLineMissionQueue.getInstance(TestActivity.this, MissionNameConstant.MISSION_KLINE);
					List<StrategyFundModel> detectModels = StrategyFundSelDao.getInstance(TestActivity.this).queryStraByOffsetDays(new Date(), -10);
					if (detectModels!=null && !detectModels.isEmpty()){
						for (int i = 0 ; i < detectModels.size(); i++){
							SelfFundHisModel sfHisModel = new SelfFundHisModel(detectModels.get(i));
							kLineMissions.addKLineMissions(sfHisModel);
						}
					}
					kLineMissions.start(TestActivity.this);
				}else if(tv.getText().equals("获取日线数据")){
					SelfFundHisModel model = new SelfFundHisModel("大连热电","600719");
					model.setKLINEPeriod(KLINE_PERIOD.DAY);
					MinPeriodKLineMission m = new MinPeriodKLineMission(mContext,model);
					m.start(mContext);
				}
			}
		});

	}


	private void saveStrategyModels(List<? extends BaseModel> models) {
		if (models==null || models.isEmpty()) return;
		List<MLObject> mlObjects = new ArrayList<>();
		for (int i = 0 ; i<models.size(); i++){
			MLObject mlObject = models.get(i).coverToMLObj();
			mlObjects.add(mlObject);
		}
		MLDataManager.saveAllInBackground(mlObjects, new SaveCallback() {
			@Override
			public void done(MLException e) {
				if (e == null){
					LOG.i("TAG", "创建成功");
				}else{
					LOG.i("TAG", "创建失败");
				}
			}
		});
	}

	@Override
	public void onResult(RESULT_CODE code, ArrayList<PendTradeModel> list) {
		if (code == RESULT_CODE.RESULT_DATAS) {
			
		}else {
			
		}
		
	}

	@Override
	public void cancel(CANCEL_CODE code, String msg) {
		// TODO Auto-generated method stub
		if (code == CANCEL_CODE.CANCEL_OK) {
			
		}else {
			
		}
	}

	@Override
	public void executeSuccess(Object result, Mission mission) {
		if (DAXIN.equals(mission.missionName)){
			Log.i("TAG",mission.missionName+"Mission Success");
		}else if (STRATEGY.equals(mission.missionName)){
			ToastUtils.showMiddleMsg(this,"加入策略数据完成");
		}
	}

	@Override
	public void executeFaile(Mission mission) {
		if (DAXIN.equals(mission.missionName)){
			Log.i("TAG",mission.missionName+"Mission Faile");
		}else if (STRATEGY.equals(mission.missionName)){
			ToastUtils.showMiddleMsg(this,"加入策略数据失败");
		}
	}



	//下面都是队列里面的方法
	@Override
	public void onMissionItemSuccess(MissionQueue queue, Mission item, Object successInfo) {
		ToastUtils.showMiddleMsg(this, "完成一项任务"+item.missionName+"成功信息:"+successInfo.toString());
		queue.executeNextMission(queue, item);
	}

	@Override
	public void onMissionItemFaile(MissionQueue queue, Mission item, Object faileInfo) {
		queue.removeMission(item);
		queue.executeNextMission(queue);
	}

	@Override
	public void onMissionQueAllFaile(MissionQueue queue) {
		ToastUtils.showMiddleMsg(this, "队列执行失败");
	}

	@Override
	public void onMissionQueComplete(MissionQueue queue) {
		ToastUtils.showMiddleMsg(this, "队列执行完毕");
	}


	@Override
	public void getPosition(PositionModel model) {

		ToastUtils.showMiddleMsg(this,"刷新资产信息成功");
	}

	@Override
	public void autoBuyResult(TRADE_ERROR_STATE state, String info) {
		switch (state){
			case ERROR_NOT_NEW_POSITION:
				CurPosition curPosition = new CurPosition();
				curPosition.requset(this);
				break;
		}
		ToastUtils.showMiddleMsg(this, info);
	}
}
